import pandas as pd
from Cal_MACD import calMACD
import matplotlib.pyplot as plt
import configparser
import logging
import os


config = configparser.ConfigParser()
config_file = r'D:\Python\My_Code_to_freedom-main\config.ini'
if not os.path.exists(config_file):
    raise FileNotFoundError(f"Configuration file '{config_file}' not found.")


config.read(config_file)
DATA_DIR = config['DEFAULT'].get('DataDir', 'stocks')
LOG_FILE = config['DEFAULT'].get('FindList', 'find_list.txt')

if not os.path.exists(DATA_DIR):
    os.makedirs(DATA_DIR)

logging.basicConfig(filename=LOG_FILE, level=logging.INFO,
                    format='%(asctime)s:%(levelname)s:%(message)s')


def get_data(stock, start='20151009', end='20241231'):
    df = pd.read_csv(f'stocks/{stock}.csv')
    df.index = pd.to_datetime(df.date)
    df = df.sort_index()
    return df.loc[start:end]


def find_macd(name, code, df):
    df = calMACD(df, 12, 26, 9)
    df.index = pd.to_datetime(df.date)
    if df.macd.iloc[-1] >= 0 and df.macd.iloc[-2] < 0:
        print(name + ':' + code)
        logging.info(name + ':' + code)


if __name__ == '__main__':
    list_macd = []
    with open('resource/macd_stocks.txt', "r") as f:
        for line in f.readlines():
            list_macd.append(line.strip('\n'))
    list_df = pd.read_csv('resource/stocks.csv')
    stock = dict(zip(list_df['名称'], list_df['代码']))

    for name in list_macd:
        code = stock[name]
        df = pd.read_csv(f'stocks/{code}.csv')
        find_macd(name, code, df)

